﻿using System;
using System.Linq;
using System.Collections.Generic;

namespace NodeSource.Result
{
    public class Row
    {
        private readonly Table _table;
        public Dictionary<Column, Object> Values { get; private set; }

        internal Row(Table table)
        {
            _table = table;
            Values = new Dictionary<Column, object>();
        }

        public KeyValuePair<Column, object> GetValue(int index)
        {
            if (index >= _table.Columns.Count
                || index < 0)
                throw new Exception(String.Format("Index specified '{0}' is out of range of table '{1}'", index, _table.Name));

            return GetValue(_table.Columns[index]);
        }

        public KeyValuePair<Column, object> GetValue(string columnName)
        {
            var column = _table.Columns.Where(c => c.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase));
            if (column.Count() == 0)
                throw new Exception(String.Format("Column specified '{0}' is not presnt in table '{1}'", columnName, _table.Name));

            return GetValue(column.First());
        }

        internal KeyValuePair<Column, object> GetValue(Column column)
        {
            return new KeyValuePair<Column, object>(column, Values[column]);
        }

        public void SetValue(int index, object value)
        {
            if (index >= _table.Columns.Count
                || index < 0)
                throw new Exception(String.Format("Index specified '{0}' is out of range of table '{1}'", index, _table.Name));

            SetValue(_table.Columns[index], value);
        }

        public void SetValue(String columnName, object value)
        {
            var column = _table.Columns.Where(c => c.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase));
            if (column.Count() == 0)
                throw new Exception(String.Format("Column specified '{0}' is not presnt in table '{1}'", columnName, _table.Name));

            SetValue(column.First(), value);
        }

        internal void SetValue(Column column, object value)
        {
            if (Values.ContainsKey(column))
                Values[column] = value;
            else
                Values.Add(column, value);
        }
    }
}
